package com.zhengsr.wanandroid.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.zhengsr.corelib.bean.ArticleCollectBean;
import com.zhengsr.corelib.bean.BaseResponse;
import com.zhengsr.corelib.bean.CollectBean;
import com.zhengsr.corelib.utils.CommonUtils;
import com.zhengsr.wanandroid.Constant;
import com.zhengsr.wanandroid.R;
import com.zhengsr.wanandroid.mvp.base.BaseActivity;
import com.zhengsr.wanandroid.mvp.base.BasePresent;
import com.zhengsr.wanandroid.mvp.contract.ContractManager;
import com.zhengsr.wanandroid.mvp.present.CollectPresent;
import com.zhengsr.zweblib.ZWebHelper;
import com.zhengsr.zweblib.widght.ZWebChromeClient;

import butterknife.BindView;

public class WebViewActivity extends BaseActivity implements ContractManager.IAddOrCancelCollect{
    private static final String TAG = "WebViewActivity";
    public static final int BANNER =  -1;
    public static final int COLLECT_TRUE =  1;
    public static final int COLLECT_FALSE =  0;
    @BindView(R.id.webview_toolbar)
    Toolbar mToolbar;
    private MenuItem mMenuItem;
    private int mCollectState;
    private CollectPresent mPresent;
    private int mArticleId;
    private int mPosition = -1;

    @Override
    public int getLayoutId() {
        return R.layout.activity_web_view;
    }

    @Override
    public BasePresent getPresent() {
        mPresent = CollectPresent.create(this);
        return mPresent;
    }

    @Override
    public void initView() {
        Intent intent = getIntent();
        if (intent == null){
            return;
        }
        Bundle bundle = intent.getExtras();
        if (bundle == null){
            return;
        }
        String url = bundle.getString("url");
        String title = bundle.getString("title");
        mCollectState = bundle.getInt("collect_state");
        mArticleId = bundle.getInt("id");
        mPosition = bundle.getInt("position");
        if (!TextUtils.isEmpty(title)) {
            mToolbar.setTitle(Html.fromHtml(title));
        }
        setSupportActionBar(mToolbar);


        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reBackData();
                finish();
            }
        });

        FrameLayout frameLayout = findViewById(R.id.web_contain);
        View errorView = LayoutInflater.from(this).inflate(R.layout.load_error_layout,null);

        //设置webview
        ZWebHelper.with(this)
                .url(url)
                .errorView(errorView)
                .parentView(frameLayout)
                .webChromeClient(new ChromeSettign())
                .go();

        WebSettings webSettings = ZWebHelper.getWebSettings();

        //缓存,自动缓存了
        webSettings.setAppCacheEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setDatabaseEnabled(true);
        if (CommonUtils.isNetworkConnected()) {
            webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        }else{
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }

    }


    private void reBackData() {
        CollectBean bean = new CollectBean();
        bean.setId(mPosition);
        if (mCollectState == COLLECT_TRUE){
            bean.setCollect(true);
        }else{
            bean.setCollect(false);
        }
        //RxBus.getInstance().post(bean);
        Intent intent = new Intent(Constant.ACTION_SEND_ARTICLE_ID);
        intent.putExtra(Constant.KEY_ARTICLE_ID,bean.getId());
        intent.putExtra(Constant.KEY_ARTICLE_COLLECT,bean.isCollect());
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }


    @Override
    public void addCollectArticleSuccess(BaseResponse<ArticleCollectBean> articleCollectBean) {
        Toast.makeText(this, R.string.add_article_success, Toast.LENGTH_SHORT).show();
        mCollectState = COLLECT_TRUE;
        showIcon();

    }

    @Override
    public void cancelCollectArticleSuccess(BaseResponse response) {
        Toast.makeText(this, R.string.cancel_article_success, Toast.LENGTH_SHORT).show();
        mCollectState = COLLECT_FALSE;
        showIcon();
    }

    class ChromeSettign extends ZWebChromeClient{
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.nar_bar,menu);
        mMenuItem = menu.findItem(R.id.menu_start);
        showIcon();
        return super.onCreateOptionsMenu(menu);
    }

    private void showIcon() {
        if (mCollectState == COLLECT_TRUE){
            mMenuItem.setIcon(R.drawable.icon_like_article_select);
        }else if (mCollectState == COLLECT_FALSE){
            mMenuItem.setIcon(R.drawable.icon_like_article_not_selected);
        }else{
            mMenuItem.setVisible(false);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_start){
            if (!mPresent.getLoginStatus()){
                Toast.makeText(this, R.string.login_first, Toast.LENGTH_SHORT).show();
                startActivity(new Intent(this,LoginInActivity.class));
            }
            if (mCollectState == COLLECT_FALSE){
                mPresent.addCollectArticle(mArticleId);
            }else{
                mPresent.cancelCollectArticle(mArticleId);
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            reBackData();
        }

        return ZWebHelper.canGoBack(keyCode)||super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        ZWebHelper.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        ZWebHelper.onPause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        ZWebHelper.onDestroy();
        super.onDestroy();
    }
}
